package com.water.camera.adapter;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.water.camera.R;
import com.water.camera.databinding.ColorItemBinding;
import com.water.camera.it.EditListener;

public class ColorAdapter extends RecyclerView.Adapter {

    int select = 0;

    int[] colorId = new int[]{R.drawable.temp_0, R.drawable.temp_1, R.drawable.temp_2, R.drawable.temp_3, R.drawable.temp_4, R.drawable.temp_5};
    int[] color = new int[]{0xffD51F1C, 0xff72A0EB, 0xff2D9A4E, 0xff2760B9, 0xff027864, 0xffFCA232};
    EditListener listener;
    int now;

    public ColorAdapter(EditListener listener, int now) {
        this.listener = listener;
        this.now = now;
        for (int i = 0; i < color.length; i++) {
            if (color[i] == now) {
                select = i;
                break;
            }
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ColorItemBinding binding = ColorItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new Holder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof Holder) {
            ((Holder) holder).bind(position);
        }
    }

    @Override
    public int getItemCount() {
        return 6;
    }

    class Holder extends RecyclerView.ViewHolder {
        ColorItemBinding binding;

        public Holder(ColorItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bind(int p) {
            if (p == select) {
                binding.img.setImageResource(R.drawable.ic_water_gou);
            } else {
                binding.img.setImageDrawable(null);
            }
            binding.img.setBackgroundResource(colorId[p]);
            itemView.setOnClickListener(v -> {
                int old = select;
                select = p;
                binding.img.setImageResource(R.drawable.ic_water_gou);
                notifyItemChanged(old);
                listener.onColorChange(color[p]);
            });
        }
    }
}
